package com.study.jdbc.database.metadata.demo;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

import org.junit.Test;

import com.study.jdbc.database.metadata.utils.DBCPUtil;

/**
* @Name: DatabaseMetaDataDemo
* @Description: 操作数据库元信息测试类
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-2-19 下午2:14:45 
* @Version: V1.0
 */
public class DatabaseMetaDataDemo {
	
	/**
	* @Name: getDatabaseInfo
	* @Description: DatabaseMetaData类：获取数据库级别基本信息
	* @Author: 李超	lc_jack@foxmail.com
	* @Version: V1.0
	* @CreateDate: 2017-2-19 下午2:15:45
	* @Parameters: 
	* @Return: void
	 */
	@Test
	public void getDatabaseInfo() throws Exception {
		Connection con = DBCPUtil.getConnection() ;
		//获取数据库元信息类
		DatabaseMetaData metaData = con.getMetaData() ;
		//打印数据库产品名称
		System.out.println(metaData.getDatabaseProductName());
		//打印数据库产品版本
		System.out.println(metaData.getDatabaseProductVersion());
		//打印数据库事务的默认隔离级别
		System.out.println(metaData.getDefaultTransactionIsolation());
		DBCPUtil.close(con, null, null) ;
	}
	
	/**
	* @Name: getSQLParameter
	* @Description: ParameterMetaData：获取sql语句参数占位符基本信息
	* @Author: 李超	lc_jack@foxmail.com
	* @Version: V1.0
	* @CreateDate: 2017-2-19 下午2:22:34
	* @Parameters: 
	* @Return: void
	 */
	@Test
	public void getSQLParameter() throws Exception {
		Connection con = DBCPUtil.getConnection() ;
		String sql = "insert into tb_items(id, name, price, detail, pic, createtime) values(?, ?, ?, ?, ?, ?) ; " ;
		PreparedStatement ps = con.prepareStatement(sql) ;
		//获取sql语句参数元信息类
		ParameterMetaData metaData = ps.getParameterMetaData() ;
		//打印sql语句参数的个数
		System.out.println(metaData.getParameterCount());
		DBCPUtil.close(con, ps, null) ;
	}
	
	/**
	* @Name: getSqlResult
	* @Description: 获取sql语句执行结果集基本信息
	* @Author: 李超	lc_jack@foxmail.com
	* @Version: V1.0
	* @CreateDate: 2017-2-19 下午2:28:32
	* @Parameters: 
	* @Return: void
	 */
	@Test
	public void getSqlResult() throws Exception {
		Connection con = DBCPUtil.getConnection() ;
		Statement s = con.createStatement() ;
		String sql = "select id, name, price, detail, pic, createtime from tb_items ; " ;
		ResultSet rs = s.executeQuery(sql) ;
		//获取sql语句执行结果元信息类
		ResultSetMetaData metaData = rs.getMetaData() ;
		//获取sql-select子句中查询字段列的个数
		int columnCount = metaData.getColumnCount() ;
		System.out.println("查询字段个数：" + columnCount);
		for (int i = 0; i < columnCount; i++) {
			//获取列名
			String columnName = metaData.getColumnName(i+1) ;
			//获取列的类型
			int columnType = metaData.getColumnType(i+1) ;
			System.out.println("字段名称：" + columnName + "-->字段类型：" + columnType);
		}
	}

}












